﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using iTextSharp.text.pdf;
using System.IO;
using System.Data;
using PPAP.BO;
using System.Configuration;

namespace PPAP.Web.Todolist
{
    public partial class UploadFile : PageBase
    {
        AttachmentTypeBO typebo = new AttachmentTypeBO();
        T_FileBO manager = new T_FileBO();
        LogBO lbo = new LogBO();
        string FJID;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
            }
        }

        protected override void SkinControl()
        {
        }

        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Button1_Click(object sender, EventArgs e)
        {
            if (Request.QueryString["RID"] != null && Request.QueryString["FJID"] != null)
            {
                FJID = Request.QueryString["FJID"];
                string FileName = file.FileName;
                if (!string.IsNullOrEmpty(FileName))
                {
                    string extension = System.IO.Path.GetExtension(FileName);//获取文件类型后缀名
                    if ((extension.ToLower() == ".pdf"))
                    {
                        int fileSize = file.PostedFile.ContentLength;
                        if (fileSize == 0)
                        {
                            base.AlertMessage("The file does not exist！");
                        }
                        else
                        {
                            if (true)//限制大小为1M
                            {
                                string filepath = ConfigurationManager.AppSettings["FilePath"];   //从配置文件中获取文件存放路径
                                string time = DateTime.Now.ToString("yyyyMMddHHmmss");
                                string FileNam_Time = "";
                                int FileIndex = FileName.LastIndexOf("\\");
                                string FName = FileName.Substring(FileIndex + 1);
                                string url = time + FName;
                                FileNam_Time = FName;//日期和名称组合
                                //string path = HttpContext.Current.Request.MapPath("../FileUpload/QYRD/" + base.CurrentUser.Name + "/");
                                //string url = "../FileUpload/QYRD/" + CurrentUser.Name + "/" + time + FileNam_Time;
                                //DirectoryInfo upDir = new DirectoryInfo(path);
                                //if (!upDir.Exists)
                                //{
                                //    upDir.Create();
                                //}
                                if (!Directory.Exists(filepath))
                                {
                                   // File.Create(filepath);
                                    System.IO.Directory.CreateDirectory(filepath);
                                }
                                file.SaveAs(filepath + time + FileNam_Time);
                                //base.Upload(filepath + time + FileNam_Time);
                                //if (File.Exists(filepath + time + FileNam_Time)) //删除服务器上的文件
                                //{
                                //    File.Delete(filepath + time + FileNam_Time);
                                //}
                                //file.SaveAs(path + FileNam_Time);
                                ///加水印
                                //string source = path + FileNam_Time; //模板路径
                                //string output = path + time + FileNam_Time; //导出水印背景后的PDF
                                //string watermark = "../FileUpload/ShuiYin/" + CurrentUser.Id + ".png";   // 水印图片
                                //DirectoryInfo upDir2 = new DirectoryInfo(HttpContext.Current.Request.MapPath("../FileUpload/ShuiYin/"));
                                //if (!upDir2.Exists)
                                //{
                                //    upDir2.Create();
                                //}
                                //if (File.Exists(watermark)) //如果存在，则删除重新生成
                                //{
                                //    File.Delete(watermark);
                                //}
                                //AddShuiYin(base.CurrentUser.Name + "(" + base.CurrentUser.Id + ")" + DateTime.Now.ToString("yyyyMMdd HHmmss"), watermark);
                                //bool isSurrcess = PDFWatermark(source, output, MapPath(watermark), 10, 10);
                                //if (isSurrcess)
                                //    File.Delete(source); //删除原文件
                                //加水印
                                //DataInfo(FJID, FileNam_Time, path + time, 0, url, (fileSize / 1024.0).ToString("n") + "kb",txtRemarks.Text,CurrentUser.Id);
                                DataInfo(FJID, FileNam_Time, filepath+time , 0, url, (fileSize / 1024.0).ToString("n") + "kb", txtRemarks.Text, CurrentUser.Id,Request.QueryString["filetype"]==null?"":Request.QueryString["filetype"].ToString(),Request.QueryString["rid"]==null?"":Request.QueryString["rid"].ToString(),"01");
                         
                                lbo.WriteLog(CurrentUser.Id, "Upload File:" + FName, Request.QueryString["RID"].ToString());
                                AlertReflashOpener("Already upload");
                            }
                        }
                    }
                    else
                    {
                        AlertMessage("Can't upload this file types,Please select a PDF file");
                    }
                }
                else
                {
                    AlertMessage("Please select accessories！");
                }
            }
        }

        /// <summary>
        /// 关闭
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Button2_Click(object sender, EventArgs e)
        {
            CloseWindow();
        }

        #region 添加水印
        /// <summary>
        /// PDF添加水印
        /// </summary>
        /// <param name="inputfilepath"></param>
        /// <param name="outputfilepath"></param>
        /// <param name="ModelPicName"></param>
        /// <param name="top"></param>
        /// <param name="left"></param>
        /// <returns></returns>
        public bool PDFWatermark(string inputfilepath, string outputfilepath, string ModelPicName, float top, float left)
        {
            PdfReader pdfReader = null;
            PdfStamper pdfStamper = null;
            try
            {
                pdfReader = new PdfReader(inputfilepath);

                int numberOfPages = pdfReader.NumberOfPages;

                iTextSharp.text.Rectangle psize = pdfReader.GetPageSize(1);

                float width = psize.Width;

                float height = psize.Height;

                pdfStamper = new PdfStamper(pdfReader, new FileStream(outputfilepath, FileMode.Create));

                PdfContentByte waterMarkContent;

                iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(ModelPicName);

                // image.Width = 200;
                // image.Height = 50;

                image.GrayFill = 20;//透明度，灰色填充
                left = width - image.Width + left;
                //top = height - image.Height - top;
                image.SetAbsolutePosition(left, top);

                //每一页加水印,也可以设置某一页加水印 
                for (int i = 1; i <= numberOfPages; i++)
                {
                    waterMarkContent = pdfStamper.GetUnderContent(i);

                    waterMarkContent.AddImage(image);
                }
                return true;
            }
            catch (Exception ex)
            {
                AlertMessage(ex.Message.Trim());
                return false;
            }
            finally
            {

                if (pdfStamper != null)
                    pdfStamper.Close();

                if (pdfReader != null)
                    pdfReader.Close();
            }
        }
        #endregion

        //添加操作
        private void DataInfo(string F_FileID, string F_Filename, string path, int type, string url, string filesize, string remarks, string upby, string filetype, string pparid, string fileversion)
        {
            manager.InsertFile(F_FileID, F_Filename, path, type, url, filesize,remarks,upby,filetype,pparid,fileversion);
        }


        #region 生成水印图片
        /// <summary>
        /// 生成水印图片
        /// </summary>
        /// <param name="Name"></param>
        /// <param name="Path"></param>
        private void AddShuiYin(string Name, string Path)
        {
            //新建一个bmp图片
            System.Drawing.Image bitmap = new System.Drawing.Bitmap(260, 20);
            //新建一个画板
            System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap);
            //设置高质量插值法
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
            //设置高质量,低速度呈现平滑程度
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            //清空画布并以透明背景色填充
            g.Clear(System.Drawing.Color.Transparent);
            //在指定位置并且按指定大小绘制原图片的指定部分
            g.DrawImage(bitmap, new System.Drawing.Rectangle(0, 0, 260, 20),

            new System.Drawing.Rectangle(0, 0, 0, 0),

            System.Drawing.GraphicsUnit.Pixel);
            System.Drawing.Font f = new System.Drawing.Font("宋体", 12);
            System.Drawing.Brush b = new System.Drawing.SolidBrush(System.Drawing.Color.Black);
            g.DrawString(Name, f, b, 2, 2);
            try
            {
                //以jpg格式保存缩略图
                bitmap.Save(MapPath(Path), System.Drawing.Imaging.ImageFormat.Png);
            }
            catch (System.Exception ex)
            {
                AlertMessage(ex.Message.ToString());
            }
            finally
            {
                bitmap.Dispose();
                //bitmap.Dispose();
                g.Dispose();
            }
        }
        #endregion


    }
}